import React, { useState, useEffect } from "react";
import {
  Button,
  Select,
  Input,
  Table,
  Image,
  Form,
  Modal,
  DatePicker,
  Radio,
} from "antd";
import { ExclamationCircleOutlined } from "@ant-design/icons";
// 引入时间格式化方法
import { formatDate } from "../../utils";
import moment from "moment";
// 引入上传图片组件
import UploadImage from "../../components/upload-image";

import API from "../../api";
import "./hp.scss";
import useFilterData from "../../hooks/useFilterData";
const { Option } = Select;

const { confirm } = Modal;

const { RangePicker } = DatePicker;

export default () => {
  const {
    currentData,
    total,
    isLoading,
    setPaginationParams,
    paginationParams,
    setFilterParams,
    getData
  } = useFilterData({
    api: API.getCompanys,
  });

  const businessTypes = [
    { label: "全部", value: "" },
    { label: "大型级以上餐饮", value: "1" },
    { label: "中型餐饮", value: "2" },
    { label: "小微型餐饮", value: "3" },
    { label: "学校食堂", value: "4" },
    { label: "托幼机构食堂", value: "5" },
    { label: "养老机构食堂", value: "6" },
    { label: "医疗机构食堂", value: "7" },
    { label: "其他", value: "8" },
  ];

  const validStatus = [
    {
      label: "全部",
      value: "",
    },
    {
      label: "正常",
      value: "NORMAL",
    },
    {
      label: "过期",
      value: "BEOVERDUE",
    },
    {
      label: "临近过期",
      value: "NEAREXPIRATION",
    },
  ];

  const dateFormatList = ["YYYY/MM/DD", "YYYY/MM/DD"];

  const [areas, setAreas] = useState([]);

  const [isModalVisible, setIsModalVisible] = useState(false);

  const [companyDataItem, setCompanyDataItem] = useState(null);

  const [deleteKeys, setDeleteKeys] = useState([]);

  // const [isOnLine, setIsOnLine] = useState(false)

  const [form] = Form.useForm();

  const [createForm] = Form.useForm();

  /**
   * 通过form里面内置的hook，来监听对应字段的变化
   * 来达到变化
   * 注意：要把监听的表单实例传进去
   *
   * useWatch 的实现思路
   *
   * 首先监听传入的form实例，当实例里面的表单发生变化的时候
   * 进行判断，判断变化的字段是否为我们传入的第一个参数字段名
   * 如果是，则把当前变化的值传出来
   */
  const isOnLine = Form.useWatch("isOnLine", createForm);

  /**
   * 模仿生命周期
   * componentDidMonth
   * 注意： 这里面不能用async
   */
  useEffect(() => {
    getAreas();
  }, []);

  const getAreas = async () => {
    const data = await API.getAreas();
    setAreas([{ name: "全部", value: "" }, ...data]);
  };

  const paginationChange = (page,size) => {
    // 修改分页数据
    console.log(page,size);
    setPaginationParams({
      ...paginationParams,
      page,
      size
    });
  };

  const updateCompany = async (data) => {
    const res = await API.getCompanyDetail(data.id);

    if (res.validStartTime || res.validEndTime) {
      res.licenceDate = [
        moment(res.validStartTime, dateFormatList[0]),
        moment(res.validEndTime, dateFormatList[1]),
      ];
    }

    /**
     * 在antd 或者 element-ui等一系列的表单控件中
     * 所有的判断都是强类型判断
     */
    if (res.areaId) {
      res.areaId = res.areaId * 1;
    }
    setCompanyDataItem(res);
  };

  useEffect(() => {
    if (companyDataItem) {
      setIsModalVisible(true);
    }
  }, [companyDataItem]);

  /**
   * 首先里面有重复逻辑
   * 这一坨代码也不应该出现在这
   */
  const columns = [
    {
      /**
       * 讯号就是我们的 1、2、3、4、
       */
      title: "序号",
      key: "id",
      render: (text, record, index) => <a>{index + 1}</a>,
    },
    {
      title: "所属辖区",
      dataIndex: "areaName",
      key: "id",
    },
    {
      title: "经营类型",
      dataIndex: "businessType",
      key: "id",
      width: 200,
      render: (text) => (
        <a>
          {businessTypes.find((item) => item.value === text) &&
            businessTypes.find((item) => item.value === text).label}
        </a>
      ),
    },
    {
      title: "门店名称",
      dataIndex: "storeName",
      key: "id",
    },
    {
      /**
       * 字段未找到,
       * 但是我们询问后端，他告诉我们，许可证开始日期+许可证结束日期就是有效期
       */
      title: "许可证有效期",
      key: "id",
      width: 240,
      render: (text, record) => {
        return (
          <a>
            {formatDate(record.validStartTime)} -
            {formatDate(record.validEndTime)}
          </a>
        );
      },
    },
    {
      /**
       * 字段未找到
       * 询问后端，该字段怎么获取，
       * 得到的结果是，直接拿licenceStatus 渲染即可
       */
      title: "许可证状态",
      dataIndex: "licenceStatus",
      key: "id",
      width: 150,
    },
    {
      title: "营业状态",
      dataIndex: "businessStatus",
      key: "id",
      render: (text, record) => {
        return <a>{text === "on" ? "营业中" : "暂停营业"}</a>;
      },
    },
    {
      title: "门头照片",
      dataIndex: "sotreImage",
      key: "id",
      render: (url) => (
        <div>
          <Image width={50} height={50} src={url} />
        </div>
      ),
    },
    {
      title: "量化等级",
      dataIndex: "quantizationLv",
      key: "id",
    },
    {
      title: "网络餐饮",
      dataIndex: "isOnLine",
      key: "id",
      render: (text) => <div>{text === 1 ? "是" : "否"}</div>,
    },
    {
      title: "阳光厨房",
      dataIndex: "isSunshine",
      key: "id",
      render: (text) => <div>{text === 1 ? "是" : "否"}</div>,
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "id",
    },
    {
      title: "操作",
      key: "id",
      fixed: "right",
      width: 180,
      render: (_, record) => (
        <div>
          <Button onClick={() => deleteData([record.id])}>删除</Button>
          &nbsp;&nbsp;
          <Button onClick={() => updateCompany(record)}>编辑</Button>
        </div>
      ),
    },
  ].map((item) => {
    return {
      width: 100,
      ...item,
    };
  });

  const onFinish = (val) => {
    setFilterParams(val);
  };

  const onFilterReset = () => {
    form.resetFields();
    setFilterParams({});
  };

  const onSelectChange = (newSelectedRowKeys) => {
    /**
     * 如果这个数组为空的话，那么说明没有选择，就要disable
     */
    setDeleteKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    onChange: onSelectChange,
  };

  const deleteData = (ids) => {
    // 调用接口，把删除数据传过去
    confirm({
      title: "是否确定删除当前数据",
      cancelText: "取消",
      okText: "确定",
      icon: <ExclamationCircleOutlined />,
      async onOk() {
        await API.deleteCompany({ ids });
        getData();
      },
    });
  };

  const handleModalCancel = () => {
    createForm.resetFields();
    setIsModalVisible(false);
  };

  useEffect(() => {
    if (!isModalVisible) {
      setCompanyDataItem(null);
    }
  }, [isModalVisible]);

  const convertCompanyForm = (data) => {
    if (data.licenceDate) {
      data.validStartTime = data.licenceDate[0];
      data.validEndTime = data.licenceDate[1];
    }

    const obj = companyDataItem || {};

    data.sotreImage = companyDataItem
      ? companyDataItem.sotreImage
      : data.sotreImage;
    data.id = obj.id;
    return data;
  };

  const handleModalOk = async () => {
    // 使用表单校验的方法，既可以校验表单，也可以拿到数据
    let data = await createForm.validateFields();

    // 劫持表单数据，并修改成后端需要的格式
    data = convertCompanyForm(data);

    /**
     * 把拿到的数据传给后端
     * 创建的时候，不需要接收返回值
     */
    const obj = companyDataItem || {};
    console.log(companyDataItem);
    await API[obj.id ? "updateCompany" : "createCompany"](data);

    createForm.resetFields();

    /**
     * 刷新列表
     */
     getData();
    setIsModalVisible(false);
  };

  const uploadSuccess = (sotreImage) => {
    const obj = companyDataItem || {};
    setCompanyDataItem({
      sotreImage,
      ...obj,
    });
  };

  return (
    <div>
      <Form
        name="basic"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        onFinish={onFinish}
        autoComplete="off"
        form={form}
      >
        <div className="company">
          <Button onClick={getData}>刷新</Button>
          &nbsp;&nbsp;
          <Button type="primary" onClick={() => setIsModalVisible(true)}>
            新增
          </Button>
          &nbsp;&nbsp;
          <Button
            type="danger"
            onClick={() => deleteData(deleteKeys)}
            disabled={deleteKeys.length === 0}
          >
            删除
          </Button>
          &nbsp;&nbsp;
          <Button>导出</Button>
          &nbsp;&nbsp;
          <div>
            <Form.Item label="所属辖区" name="areaId">
              <Select style={{ width: 120 }}>
                {areas.map((item) => (
                  <Option key={item.name} value={item.id}>
                    {item.name}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </div>
          &nbsp;&nbsp;
          <div>
            <Form.Item label="经营类型" name="businessType">
              <Select style={{ width: 120 }}>
                {businessTypes.map((item) => (
                  <Option key={item.label} value={item.value}>
                    {item.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </div>
          &nbsp;&nbsp;
          <div>
            <Form.Item label="许可证状态" name="validStatus">
              <Select style={{ width: 120 }}>
                {validStatus.map((item) => (
                  <Option key={item.label} value={item.value}>
                    {item.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </div>
          &nbsp;&nbsp;
          <Form.Item name="keyWord">
            <Input style={{ width: "120px" }} placeholder="请输入"></Input>
          </Form.Item>
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
          &nbsp;&nbsp;
          <Button onClick={onFilterReset} htmlType="button">
            重置
          </Button>
        </div>
      </Form>
      <Table
        style={{ marginTop: "20px" }}
        columns={columns}
        dataSource={currentData}
        scroll={{
          x: 800,
          y: 200,
        }}
        pagination={{
          total,
          defaultPageSize: paginationParams.size,
          onChange: paginationChange,
        }}
        loading={isLoading}
        rowSelection={rowSelection}
      />
      <Modal
        title="新增"
        visible={isModalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
      >
        <Form
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          initialValues={companyDataItem}
          autoComplete="off"
          form={createForm}
        >
          <Form.Item label="所属辖区" name="areaId">
            <Select style={{ width: 120 }}>
              {areas
                .filter((item) => !!item.id)
                .map((item) => (
                  <Option key={item.name} value={item.id}>
                    {item.name}
                  </Option>
                ))}
            </Select>
          </Form.Item>
          <Form.Item label="经营类型" name="businessType">
            <Select style={{ width: 120 }}>
              {businessTypes
                .filter((item) => !!item.value)
                .map((item) => (
                  <Option key={item.label} value={item.value}>
                    {item.label}
                  </Option>
                ))}
            </Select>
          </Form.Item>
          <Form.Item label="门店名称" name="storeName">
            <Input></Input>
          </Form.Item>
          <Form.Item label="单位名称" name="companyName">
            <Input></Input>
          </Form.Item>
          <Form.Item label="许可证号" name="licenceNum">
            <Input></Input>
          </Form.Item>
          <Form.Item label="有效日期" name="licenceDate">
            <RangePicker />
          </Form.Item>
          <Form.Item label="社会统一信用代码" name="socialCreditCode">
            <Input></Input>
          </Form.Item>
          <Form.Item label="门店地址" name="storeAddress">
            <Input></Input>
          </Form.Item>
          <Form.Item label="营业状态" name="businessStatus">
            <Radio.Group>
              <Radio value={"on"}>正常营业</Radio>
              <Radio value={"off"}>暂停营业</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="法人" name="legalPerson">
            <Input></Input>
          </Form.Item>
          <Form.Item label="联系电话" name="tel">
            <Input></Input>
          </Form.Item>
          <Form.Item label="门店照片" name="sotreImage">
            <UploadImage uploadSuccess={uploadSuccess}></UploadImage>
          </Form.Item>
          <Form.Item label="量化等级" name="quantizationLv">
            <Radio.Group>
              <Radio value={"A"}>A</Radio>
              <Radio value={"B"}>B</Radio>
              <Radio value={"C"}>C</Radio>
              <Radio value={"D"}>未定级</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="网络餐饮" name="isOnLine">
            <Radio.Group>
              <Radio value={true}>是</Radio>
              <Radio value={false}>否</Radio>
            </Radio.Group>
          </Form.Item>
          {isOnLine && (
            <Form.Item label="阳光厨房" name="isSunshine">
              <Radio.Group>
                <Radio value={true}>是</Radio>
                <Radio value={false}>否</Radio>
              </Radio.Group>
            </Form.Item>
          )}
        </Form>
      </Modal>
    </div>
  );
};
